package linter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import linter.POJO.DO.ClassData;
import linter.POJO.DO.ClassDataUploader;
import linter.POJO.DO.UserClass;
import linter.POJO.DO.UserClassPlan;
import linter.POJO.DTO.ClassDataDTO;
import linter.POJO.DTO.classDataUploaderDTO;
import linter.mapper.ClassDataMapper;
import linter.mapper.ClassDataUploaderMapper;
import linter.mapper.UserClassMapper;
import linter.mapper.UserClassPlanMapper;
import linter.service.ClassDataService;
import linter.service.ClassFileService;
import linter.utils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static linter.custom.Constant.*;
import static linter.custom.CustomResultType.*;
import static linter.utils.ModelUtils.generateUUID;

/**
* @author 北煜
* @description 针对表【class_data】的数据库操作Service实现
* @createDate 2024-04-10 11:36:23
*/
@Service
public class ClassDataServiceImpl extends ServiceImpl<ClassDataMapper, ClassData>
    implements ClassDataService{
    @Resource
    ClassDataMapper classDataMapper;
    @Resource
    ClassFileService classFileService;
    @Resource
    UserClassMapper userClassMapper;
    @Resource
    UserClassPlanMapper userClassPlanMapper;
    @Resource
    ClassDataUploaderMapper classDataUploaderMapper;

    @Override
    public String uploadClass(classDataUploaderDTO classDataUploaderDTO) {
        Date date = new Date();
        ClassData classData = new ClassData();
        classData.setClassTitle(classDataUploaderDTO.getClassData().getClassTitle());
        classData.setClassImage(DEFAULT_IMG_URL_NOTE);
        classData.setClassNode(classDataUploaderDTO.getClassData().getClassNode());
        classData.setClassType(classDataUploaderDTO.getClassData().getClassType());
        classData.setClassContent(classDataUploaderDTO.getClassData().getClassContent());
        classData.setClassSource(classDataUploaderDTO.getClassData().getClassSource());
        classData.setCreateTime(date);
        classData.setUpdateTime(date);

        ClassDataUploader classDataUploader = new  ClassDataUploader();
        classDataUploader.setUserId(classDataUploaderDTO.getUserId());
        classDataUploader.setClassSource(classDataUploaderDTO.getClassData().getClassSource());
//        classDataUploader.setClassDataId();
        int flag = classDataMapper.insert(PropertyUtils.doToDto(classData, ClassData.class));

        return flag != 1 ? UPLOAD_ERROR : UPLOAD_SUCCESS;

    }

    @Override
    public PageInfo<ClassDataDTO> getAllClass() {
        PageHelper.startPage(1, 10);
        int node = 1;
        List<ClassDataDTO> list = classDataMapper.selectByTypeAndNode(node);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<ClassDataDTO> getLearningClass(List<UserClassPlan> list) {
        // 得到classType
        List<String> classTypes = list.stream().map(UserClassPlan::getClassType).collect(Collectors.toList());
        // 构建查询条件
        QueryWrapper<ClassData> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("class_type", classTypes);
        // 设置分页参数
//        TODo
        PageHelper.startPage(1, 10);
        // 调用mapper方法进行查询
        List<ClassData> classDataList = classDataMapper.selectList(queryWrapper);
        // 将查询结果转换为DTO对象列表
        List<ClassDataDTO> classDataDTOList = PropertyUtils.listToList(classDataList, ClassDataDTO.class);
        // 清理可能存在的null元素（根据listToList方法的实现，如果转换失败可能会返回null）
        classDataDTOList = classDataDTOList.stream().filter(Objects::nonNull).collect(Collectors.toList());
        return new PageInfo<>(classDataDTOList);
    }

    @Override
    public ClassDataDTO getClassByClassId(Integer classId) { return classDataMapper.selectByClassId(classId); }

    @Override
    public String uploadClassImage(MultipartFile file, String classType, String className, Long classId) {
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY_QINIU, SECRET_KEY_QINIU);
        String bucketName = BUCKET_NAME_QINIU;
        String key = "class/" + classType + "/" + generateUUID() + className;
        // 保存在数据库中，到时候进行拼接
        String baseUrl = "http://qiniuyun.linter.top";
        String url = baseUrl + "/" + key;
        String save = classFileService.saveByClassId(classId, classType, className, url);
        if (Objects.equals(save, SAVE_NOT_ERROR)){ return SAVE_NOT_ERROR; }
        byte[] fileContent = new byte[0];
        try {
            fileContent = file.getBytes();
            try(ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContent)){
                String upToken = auth.uploadToken(bucketName);
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                if (response.statusCode == RES_SUCCESS) {
                    return putRet.hash + ": " + UPLOAD_SUCCESS;
                } else {
                    throw new RuntimeException(UPLOAD_ERROR + ": " + response.bodyString());
                }
            }catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageInfo<ClassDataDTO> getClassByClassName(String classTitle, String classType) {
        PageHelper.startPage(1, 10);
        QueryWrapper<ClassData> queryWrapper = new QueryWrapper<>();
        // 初始化查询条件，同时考虑 classTitle 和 classType
        if (classTitle != null) { queryWrapper.like("class_title", "%" + classTitle + "%"); }
        if (classType != null) { queryWrapper.or().like("class_type", "%" + classType + "%"); }
        // 如果两个条件都没有，直接返回 null
        if (classTitle == null && classType == null) { return null; }
        // 执行查询
        List<ClassData> classDataList = classDataMapper.selectList(queryWrapper);
        // 如果没有查询结果，返回 null
        if (CollectionUtils.isEmpty(classDataList)) { return null; }
        // 转换为DTO并封装到PageInfo中
        List<ClassDataDTO> classDataDTOS = PropertyUtils.listToList(classDataList, ClassDataDTO.class);
        return new PageInfo<>(classDataDTOS);
    }

    @Override
    public PageInfo<ClassDataDTO> getFinishClass(Long uuid) {
        PageHelper.startPage(1, 10);
        QueryWrapper<UserClass> queryWrapper = new QueryWrapper<>();
        List<UserClass> userClassList = userClassMapper.selectList(queryWrapper
                .eq("uuid",uuid).eq("is_finish",2));
        List<AbstractMap.SimpleEntry<String, Integer>> combinedList = userClassList.stream()
                .map(userClass -> new AbstractMap.SimpleEntry<>(userClass.getClassType(), userClass.getClassNode()))
                .collect(Collectors.toList());
        List<ClassData> list = new ArrayList<>();
        for (AbstractMap.SimpleEntry<String, Integer> entry : combinedList){
            QueryWrapper<ClassData> queryWrapper1 = new QueryWrapper<>();
            ClassData classData = classDataMapper.selectOne(queryWrapper1.eq("class_type",entry.getKey())
                    .eq("class_node",entry.getValue()));
            if (classData != null){ list.add(classData); }
        }
        return new PageInfo<>(PropertyUtils.listToList(list, ClassDataDTO.class));
    }


    public PageInfo<classDataUploaderDTO> AllClass(int pageNum) {
        QueryWrapper<ClassDataUploader> queryWrapper = new QueryWrapper<>();
        List<ClassDataUploader> uploaderList = classDataUploaderMapper.selectList(queryWrapper);

//         使用 Stream API 结合 Map 和 Function 接口来转换数据
        List<classDataUploaderDTO> CDUList = uploaderList.stream()
                .map(classDataUploader -> {
                    classDataUploaderDTO dto = new classDataUploaderDTO();
                    dto.setClassData(classDataMapper.selectByClass(classDataUploader.getId()));
                    dto.setUserId(classDataUploader.getUserId());
                    dto.setIsFinish(classDataUploader.getIsFinish());
                    return dto;
                })
                .collect(Collectors.toList());

        return new PageInfo<>(CDUList);
//        return new PageInfo<>();
    }

    @Override
    public PageInfo<ClassData> getClassByClassType(String classType) {
        PageHelper.startPage(1, 10);
        QueryWrapper<ClassData> queryWrapper = new QueryWrapper<>();
        List<ClassData> list = classDataMapper.selectList(queryWrapper
                .eq("class_type",classType).eq("is_delete", 0));
        return new PageInfo<>(list);
    }
}




